<?php
declare (strict_types = 1);

namespace app\common\model;

use think\Model;
use app\common\lib\Ali;

/**
 * @mixin \think\Model
 */
class Poem extends Model
{
    public $error = '';

    //
    public function getLineListAttr()
    {
        return \explode("\r\n", $this->content);
    }

    /**
     * 根据行数返回上下句
     */
    public function getLine($line)
    {
        $list = $this->getLineListAttr();
        return $this->splitLine($list[$line]);
    }

    /**
     * 生成上下句
     */
    public function splitLine($lineText)
    {
        $len = strlen($lineText) / 2;
        $lineMap = [
            substr($lineText, 0, $len - 3),
            substr($lineText, $len, - 3)
        ];
        return $lineMap;
    }

    /**
     * 生成题目
     *
     * @return void
     * @author Ymob
     * @date 2021-04-23 00:09:54
     */
    public function createQuestion()
    {
        $arr = [];
        $ali = Ali::getClint();
        $recordList = [];
        $oldData = Question::where('poem_id', $this->id)
            ->field([
                'id',
                'concat(line, "-", type)' => 'key',
                'record'
            ])
            ->select()->toArray();
        $map = array_column($oldData, 'id', 'key');
        foreach ($this->getLineListAttr() as $line => $lineText) {
            $lineMap = $this->splitLine($lineText);
            for ($i = 0; $i < 2; $i++) {
                if (!$ali->tts($lineMap[$i] . ($i ? '。请背诵上句' : '。请背诵下句'))) {
                    $this->error = $ali->error;
                    $ali->removeRecord($recordList);
                    return false;
                }
                $temp = [
                    'poem_id' => $this->id,
                    'line' => $line,
                    'type' => $i,
                    'record' => $ali->filePath,
                ];
                $index = "{$line}-{$i}";
                if (isset($map[$index])) {
                    $temp['id'] = $map[$index];
                }
                $arr[] = $temp;
                $recordList[] = $ali->filePath;
            }
        }
        if ((new Question)->saveAll($arr)) {
            $ali->removeRecord(array_column($oldData, 'record'));
            return true;
        } else {
            $this->error = '数据库写入失败';
            $ali->removeRecord($recordList);
            return false;
        }
    }
}
